package com.cchc.k8s.kernel;

import com.cchc.k8s.Constants;
import com.cchc.k8s.request.CreateServiceRequest;
import io.kubernetes.client.custom.IntOrString;
import io.kubernetes.client.openapi.models.V1ObjectMeta;
import io.kubernetes.client.openapi.models.V1Service;
import io.kubernetes.client.openapi.models.V1ServicePort;
import io.kubernetes.client.openapi.models.V1ServiceSpec;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * file：ServiceBuilder.java
 * description:
 * date: 2021-09-22 14:51
 * author: wenrui
 * version: 1.0
 */
@Component
public class ServiceBuilder {

    public V1Service build(CreateServiceRequest request) {
        V1Service service = new V1Service();

        V1ObjectMeta v1ObjectMeta = new V1ObjectMeta().name(request.getServiceName() + "-svc");

        V1ServiceSpec v1ServiceSpec = new V1ServiceSpec();
        // ports
        List<V1ServicePort> servicePorts = new ArrayList<>();
        V1ServicePort servicePort = new V1ServicePort();
        servicePort.targetPort(new IntOrString(request.getPort()));
        servicePort.port(request.getPort());
        servicePorts.add(servicePort);
        v1ServiceSpec.ports(servicePorts);

        // selector 与deployment的标签匹配
        Map<String,String> map = new HashMap<>(1);
        map.put("app", request.getServiceName());
        v1ServiceSpec.selector(map);

        // type 默认ClusterIP
        if (request.getType() != null) {
            v1ServiceSpec.setType(request.getType().name());
            if (request.getType().name().equals("ExternalName")) {
                v1ServiceSpec.externalName(request.getOtherServiceName() + "." + request.getOtherServiceName());
            }
        }

        service.apiVersion(Constants.API_VERSION)
                .kind("Service")
                .metadata(v1ObjectMeta)
                .spec(v1ServiceSpec);

        return service;
    }
}
